<?php

class Categories extends CI_Controller {
    
    private $_auth;
    public function __construct() {
        parent::__construct();
        $this->_auth = $this->myclass->checkuser();
        if($this->_auth == FALSE) redirect ("backend/home");
    }
    
    public function index(){
        $data['data']['parcat'] = $this->mcategories->getParentCat();
        $data['title'] = "Bảng danh mục";
        $data['temp'] = "backend/categories/home";
        $this->load->view("backend/layout/index",$data);
    }
    
    public function add(){
        if($this->input->post("add")){
            $post = $this->input->post("data");
        }
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $this->form_validation->set_rules('data[name]', 'Tên danh mục', 'required');
        if ($this->form_validation->run() == TRUE){
            $this->mcategories->insert($post);
            redirect("backend/categories");
        }
        $data['data']['parcat'] = $this->mcategories->getParentCat();
        $data['title'] = "Bảng danh mục";
        $data['temp'] = "backend/categories/form";
        $this->load->view("backend/layout/index",$data);
    }
    
    public function delete($id){
        $this->mcategories->delete($id);
        $this->mcategories->deleteByParentId($id);
        $this->mproducts->deleteByCid($id);
        redirect("backend/categories");
    }
    public function deleteall(){
        $this->mcategories->deleteAll();
        redirect("backend/categories");
    }
    
    public function update($id){
        if($this->input->post("add")){
            $post = $this->input->post("data");
        }
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $this->form_validation->set_rules('data[name]', 'Tên danh mục', 'required');
        if ($this->form_validation->run() == TRUE){
            $this->mcategories->update($id,$post);
            redirect("backend/categories");
        }
        $data['data']['cat']= $this->mcategories->fetchOne($id);
        $data['data']['parcat'] = $this->mcategories->getParentCat();
        $data['title'] = "Sửa danh mục";
        $data['temp'] = "backend/categories/form";
        $this->load->view("backend/layout/index",$data);
    }
}
